import requests
from requests import JSONDecodeError
from selectolax.parser import HTMLParser

from dc_shop.core.models.enums.currency import Currency


def convert_currency(summ: float, exchange_rate: float, exchange_percent: float | None = None) -> float:
    """Конвертируем из одной валюты в другую"""

    converted = summ / exchange_rate

    if exchange_percent:
        converted += (converted / 100) * exchange_percent

    return converted


def get_currency_rate(currency_to: Currency) -> float | bool:
    """Получаем курс валют c биржи okx"""

    headers = {
        "authority": "www.okx.com",
        "accept": "application/json",
        "accept-language": "en-GB,en-US;q=0.9,en;q=0.8",
        "app-type": "web",
        "cache-control": "no-cache",
        "pragma": "no-cache",
        "referer": "https://www.okx.com/ru/convert",
        "sec-ch-ua": '"(Not(A:Brand";v="99", "Chromium";v="115", "Google Chrome";v="115"',
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": '"Windows"',
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.5842.194 Safari/537.36",
        "x-cdn": "https://static.okx.com",
        "x-locale": "ru_RU",
        "x-site-info": "{}",
        "x-utc": "3",
        "x-zkdex-env": "0",
    }

    params = None
    if currency_to == Currency.ton:
        url = f"https://www.okx.com/ru/convert/{currency_to.value}-to-thb"
    else:
        params = {
            "t": "1697541923463",
            "cryptoCurrency": currency_to.value.upper(),
            "fiatCurrency": "THB",
            "side": "sell",
        }
        url = "https://www.okx.com/v3/c2c/tradingOrders/mostUsedPaymentAndBestPriceAds"

    r = requests.get(url, params=params, headers=headers)
    if not r.status_code == 200:
        return False

    if currency_to == Currency.ton:
        tree = HTMLParser(r.text)
        try:
            rate = tree.css_first("div.fiat-or-quote-number").text()
            rate = rate.replace("฿", "").replace(",", ".").strip()
            return float(rate)
        except (AttributeError, ValueError):
            return False
    else:
        try:
            content = r.json()
        except JSONDecodeError:
            return False

        offers = content["data"]
        if len(offers) == 0:
            return False
        for offer in offers:
            if offer["bestOption"]:
                return float(offer["unitPrice"])

        return float(offers[0]["unitPrice"])
